<template>
  <button
    @click.stop="handleOpenVote(titem)"
    :class="{ VoteIsNotCreated: !teacherIsCreateVote(titem.taskID) }"
    :disabled="!teacherIsCreateVote(titem.taskID)"
  >
    参与投票
  </button>
</template>

<script>
import { createVoteItem } from "@/request/vote";
import { mapState } from "vuex";
export default {
  data() {
    return {};
  },
  props: {
    nTaskSettings: Object,
    courseInfo: Object,
    titem: Object,
  },
  computed: {
    ...mapState({
      userInfo: (state) => state.user.userInfo,
    }),
    teacherIsCreateVote() {
      return (taskID) => {
        return this.nTaskSettings?.[taskID]?.voteID;
      };
    },
  },
  methods: {
    // 打开投票界面
    async handleOpenVote(titem) {
      let timeSetting =
        this.nTaskSettings[titem.taskID] ||
        this.courseInfo.taskSettings[titem.taskID];
      let currTime = new Date().getTime();
      if (
        timeSetting.cutOffTime &&
        this.toMs(timeSetting.cutOffTime) < currTime &&
        timeSetting.state == "生效"
      ) {
        return this.$antdMessage.warning({
          content: "已超出任务限定学习时间！",
        });
      }
      // this.$antdMessage.warning({content: "正在开发!"})
      return await this.handleCreateVote();
    },
    toMs(data) {
      return !data ? 0 : new Date(data).getTime();
    },
    handleCreateVote() {
      return new Promise((resolve, reject) => {
        const params = {
          voteID: this.teacherIsCreateVote(this.titem.taskID),
          userID: this.userInfo.userID,
          title:
            this.userInfo.realName ||
            this.userInfo.nickName ||
            this.userInfo.email ||
            this.userInfo.regName,
          state: "正常",
          itemDetailLink: "",
          itemPicPath: this.userInfo.iconPath,
          itemDesc: "",
        };
        // 获取当前任务
        // 判断studyData是否存在 且是否有内容
        const currNo = this.courseInfo.currNo
        let localData = localStorage.getItem("studyData");
        localData = localData ? JSON.parse(localData) : {};
        if (!localData[currNo]) localData[currNo] = {}
        let mystudydata = localData[currNo]?.[this.userInfo.userID];
        if (!mystudydata) {
          mystudydata = [];
        }
        const oldTaskResult = mystudydata.find(
          (item) => item.taskID == this.titem.taskID
        );
        let guidelineID = null;
        let guideline = {};
        Object.keys(oldTaskResult.guidelineResults).forEach((key, index) => {
          if (index == 0)
            (guidelineID = key) &&
              (guideline = oldTaskResult.guidelineResults[key]);
        });
        if (guideline.submitContent?.data) {
          params.itemDetailLink = guideline.submitContent.data.showLink;
        } else {
          this.$antdMessage.error({ content: "获取到的网址链接为空!" });
          return resolve(false)
        }
        createVoteItem(params)
          .then((res) => {
            if (res.errno == 0) {
              this.$antdMessage.success({ content: "已成功参与投票!" });
              // console.log(oldTaskResult, oldTaskResult.guidelineResults[guidelineID]);
              oldTaskResult.guidelineResults[guidelineID].voteItemID = res.data.voteItemID;
              localData[currNo][this.userInfo.userID] = mystudydata;
              localStorage.setItem("studyData", JSON.stringify(localData));
              this.$emit("SaveVoteItemID", this.titem, res.data.voteItemID)
              return resolve(true)
            } else {
              this.$antdMessage.error({
                content: res.message || "参与投票失败!",
              });
              return resolve(false)
            }
          })
          .catch((err) => {
            this.$antdMessage.error({ content: err || "请求异常!" });
            return resolve(false)
          });
      })
    },
  },
};
</script>

<style lang="stylus"></style>